<template>
  <div class="edit-page-wrap">
    <Head title="通知信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="edit-form-wrap"
        >
          <el-form-item label="通知标题" prop="noticeTitle">
            <el-input
              v-model.trim="ruleForm.noticeTitle"
              placeholder="请输入通知标题"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="通知内容" prop="noticeContent" class="has-tips">
            <el-input
              v-model.trim="ruleForm.noticeContent"
              placeholder="请输入通知内容"
              maxlength="200"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
            <div class="tip">
              <div class="icon"></div>
              选择“短信发放”模式时，“通知内容”需要配置为在短信平台审核通过的模板ID
            </div>
          </el-form-item>
          <el-form-item label="发送时间" prop="sendingTime">
            <div class="time-wrap">
              <el-date-picker
                v-model="ruleForm.sendingTime1"
                value-format="YYYY-MM-DD"
                popper-class="qc-date"
                placeholder="请选择日期"
                type="date"
                @change="handleTime"
              />
            </div>
            <div class="time-wrap time-wrap1">
              <el-time-select
                v-model="ruleForm.sendingTime2"
                start="00:00"
                step="00:10"
                end="23:50"
                placeholder="请选择时间"
                @change="handleTime"
              />
            </div>
          </el-form-item>
          <el-form-item label="发送方式" prop="sendingMethod">
            <el-radio-group
              v-model="ruleForm.sendingMethod"
              v-for="(item, index) in NOTICE_METHOD"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="发送对象" prop="sendingObject" class="has-tips">
            <el-radio-group
              v-model="ruleForm.sendingObject"
              v-for="(item, index) in optionsS.noticeObj"
              :key="index"
              @change="handleSendObject"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div v-if="ruleForm.sendingObject" class="tip">
              <div class="icon"></div>
              {{ getSendObjectTip() }}
            </div>
          </el-form-item>
          <el-form-item
            label=""
            prop="treeVehicles"
            v-if="ruleForm.sendingObject === '1'"
          >
            <QcTree
              ref="treeVehiclesRef"
              :data="optionsS.vehicle"
              :showCheckbox="true"
              :checkStrictly="true"
              :setCheckedKeys="ruleForm.treeVehicles"
              @handleCheck="handleCheckVehicles"
            ></QcTree>
          </el-form-item>
          <el-form-item label="" v-if="ruleForm.sendingObject == '2'">
            <el-button type="primary" plain @click="clickUploadUser"
              >批量导入</el-button
            >
          </el-form-item>
          <el-form-item
            prop="importUsers"
            v-if="ruleForm.sendingObject === '2'"
          >
            <el-input
              v-model.trim="ruleForm.importUsers"
              placeholder="请输入用户账号"
              type="textarea"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
    <ImportDialog ref="importDialogRef" @user-data="userData"></ImportDialog>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import ImportDialog from '@/components/qcDialog/importDialog.vue';
import { FormRules, FormInstance } from 'element-plus';
import { NOTICE_METHOD, NOTICE_OBJECT } from '@/utils/dictionaries';
import {
  saveNotice,
  updateNotice,
  queryNoticeDetail,
} from '@/service/apis/market';
import { queryVehicle } from '@/service/apis/org';
import { NO_CHINESE_COMMA } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const importDialogRef = ref();
const treeVehiclesRef = ref();

const optionsS = reactive({
  vehicle: [] as any,
  noticeObj: NOTICE_OBJECT,
});

// 获取车辆机构
const getVehicle = () => {
  queryVehicle({}).then((res: any) => {
    if (res) {
      optionsS.vehicle = res;
    }
  });
};

const getSendObjectTip = () => {
  if (ruleForm.sendingObject === '0') {
    return '所有用户均为发送目标';
  } else if (ruleForm.sendingObject === '1') {
    return '选定企业后，该企业所有用户均为发送目标，含任务执行前新增的用户';
  } else if (ruleForm.sendingObject === '2') {
    return `注：请输入用户的账号，多个账号之间用英文', '隔开`;
  }
  return '';
};

const ruleForm: any = reactive({
  noticeTitle: '', // 通知标题
  noticeContent: '', // 通知内容

  sendingTime: '', // 发送时间
  sendingTime1: '',
  sendingTime2: '',
  sendingMethod: '0', // 发送方式
  sendingObject: '0', // 发送对象

  targetIds: '', // 发送企业/用户
  treeVehicles: [] as any,
  importUsers: '',
});

const checkTreeVehicles = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeVehiclesRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (ruleForm.sendingObject === '1' && arr.length === 0) {
    callback(new Error('请选择具体的用户企业（车辆机构）'));
  }
  callback();
};
const rules = reactive<FormRules>({
  noticeTitle: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
  noticeContent: [
    { required: true, message: '请输入通知内容', trigger: 'blur' },
  ],
  sendingTime: [
    { required: true, message: '请选择发送时间', trigger: ['blur', 'change'] },
  ],
  sendingMethod: [
    { required: true, message: '请选择发送方式', trigger: ['blur', 'change'] },
  ],
  treeVehicles: [
    { required: true, message: '请选择企业', trigger: ['blur', 'change'] },
    { validator: checkTreeVehicles, trigger: ['blur', 'change'] },
  ],
  importUsers: [
    {
      required: true,
      message: '请导入或输入用户',
      trigger: ['blur', 'change'],
    },
    { pattern: NO_CHINESE_COMMA, message: '不能输入中文逗号', trigger: 'blur' },
  ],
});

const handleTime = () => {
  if (ruleForm.sendingTime1 && ruleForm.sendingTime2) {
    ruleForm.sendingTime = `${ruleForm.sendingTime1} ${ruleForm.sendingTime2}:00`;
  } else {
    ruleForm.sendingTime = '';
  }
};

const handleSendObject = (val: any) => {
  if (val === '1' && optionsS.vehicle.length === 0) {
    getVehicle();
  }
};

const handleCheckVehicles = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeVehicles = checkedChildData;
};

const clickUploadUser = () => {
  importDialogRef.value?.show();
};

const userData = (data: any) => {
  ruleForm.importUsers = data;
};

const orgId = window.localStorage.getItem('orgId') || '';
if (orgId) {
  optionsS.noticeObj = NOTICE_OBJECT.filter((item: any) => item.value !== '0');
  ruleForm.sendingObject = '1';
}
if (id) {
  queryNoticeDetail({ id: id }).then((res: any) => {
    if (res) {
      for (const key in ruleForm) {
        if (res[key]) {
          ruleForm[key] = res[key];
        }
      }
      ruleForm.sendingTime1 = res.sendingTime.substring(0, 10);
      ruleForm.sendingTime2 = res.sendingTime.substring(11, 16);

      if (ruleForm.sendingObject === '1') {
        ruleForm.treeVehicles = res.targetIds.split(',');
        getVehicle();
      } else if (ruleForm.sendingObject === '2') {
        ruleForm.importUsers = res.targetIds;
      }
    }
  });
} else {
  if (orgId) {
    getVehicle();
  }
}

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }

  const form: any = {
    noticeTitle: ruleForm.noticeTitle,
    noticeContent: ruleForm.noticeContent,
    sendingTime: ruleForm.sendingTime,
    sendingMethod: ruleForm.sendingMethod,
    sendingObject: ruleForm.sendingObject,
    targetIds: '',
  };
  if (ruleForm.sendingObject === '1') {
    // form.targetIds = ruleForm.treeVehicles.toString();
    const arr: any = [];
    const treeOrg = treeVehiclesRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        arr.push(item.id);
      }
    });
    form.targetIds = arr.toString();
  } else if (ruleForm.sendingObject === '2') {
    form.targetIds = ruleForm.importUsers;
  }
  console.log('rr----', form);
  if (id) {
    form.id = id;
    updateNotice(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    saveNotice(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>

<style lang="scss" scoped>
.time-wrap {
  display: flex;
  :deep(.el-select-v2),
  :deep(.el-input),
  :deep(.el-select),
  :deep(.el-input__wrapper) {
    width: 135px !important;
  }
}
.time-wrap1 {
  margin-left: 30px;
}
</style>